﻿using UnityEngine;

namespace Core
{
    public class CameraFollowInRange : Core.Component, IAwake, ILateUpdate
    {
        public Transform Target { get; private set; }
        public Vector2 Range = new(0.3f, 0.7f);

        public bool Enabled;

        public void Awake()
        {
            Enabled = true;
        }

        public void Follow(Transform trans)
        {
            if (trans == null)
            {
                return;
            }

            Target = trans;
        }

        private bool Within(float value, Vector2 range)
        {
            return value >= range.x && value <= range.y;
        }

        public void LateUpdate()
        {
            if (Enabled == false || Target == null || Camera.main == null)
            {
                return;
            }

            var cam = Camera.main;

            var transform = cam.transform;

            // 计算目标位置在屏幕上的坐标
            Vector3 pos = cam.WorldToViewportPoint(Target.position);

            if (Within(pos.x, Range) && Within(pos.y, Range))
            {
                return;
            }

            pos.x = Mathf.Clamp(pos.x, Range.x, Range.y);
            pos.y = Mathf.Clamp(pos.y, Range.x, Range.y);

            Vector3 delta = Target.position - cam.ViewportToWorldPoint(pos);

            Vector3 destination = transform.position + delta;

            transform.position = destination;
            //transform.position = Vector3.Lerp(transform.position, destination, smoothSpeed * Time.deltaTime);
        }
    }
}
